package com.cneport.das.common.validate;


import com.cneport.das.common.utils.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Desc 校验实现
 * @Ver 1.0
 * @Author GavinZhang
 * @Company 东方物通科技有限（北京）公司
 * @Date 2021-12-28 10:35:07
 */
public class FieldCheckHolder {
    public static final IValidator<String> STRING = newStringVal();
    public static final IValidator<String> DATE_STR = new IValidator<String>() {
        @Override
        public ResultVO validate(FieldCheck fv, String fieldName,
                                 String fieldVal, ResultVO resultVO) {
            resultVO = checkNullAndLen(fv, fieldName, fieldVal, resultVO);

            if (!StringUtil.isEmpty(fieldVal)
                    && !StringUtil.isEmpty(fv.regex())) {
                if (!validateDate(fieldVal, fv.regex())) {
                    resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                            + fieldVal + "]日期不合法或不能匹配格式 " + fv.regex());
                }
            }
            boolean rs = validateIn(fieldVal, fv.in());
            if (!rs) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                        + fieldVal + "]不在范围内（ " + fv.in() + "）");
            }
            return resultVO;
        }
    };
    public static final IValidator<Double> DOUBLE = new IValidator<Double>() {
        @Override
        public ResultVO validate(FieldCheck fv, String fieldName,
                                 Double fieldVal, ResultVO resultVO) {
            if (!fv.isNullable() && fieldVal == null) {
                resultVO.addError(fv.name() + "[" + fieldName + "]为空！");
            }

            if (fv.minVal() != -1d && fieldVal < fv.minVal()) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值[" + fieldVal + "]小于最小值[" + fv.minVal() + "]！");
            }
            if (fv.maxVal() != -1d && fieldVal > fv.maxVal()) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值[" + fieldVal + "]大于最大值[" + fv.maxVal() + "]！");
            }

            if (!StringUtil.isBlank(fv.in()) && fieldVal < fv.minVal()) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值[" + fieldVal + "]小于最小值[" + fv.minVal() + "]！");
            }
            boolean rs = validateIn(fieldVal, fv.in());
            if (!rs) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                        + fieldVal + "]不在范围内（ " + fv.in() + "）");
            }
            return resultVO;
        }
    };

    public static final IValidator<Integer> INTEGER = new IValidator<Integer>() {
        @Override
        public ResultVO validate(FieldCheck fv, String fieldName,
                                 Integer fieldVal, ResultVO resultVO) {
            if (!fv.isNullable() && fieldVal == null) {
                resultVO.addError(fv.name() + "[" + fieldName + "]为空！");
            }

            if (fv.min() != -1d && fieldVal < fv.min()) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值[" + fieldVal + "]小于最小值[" + fv.min() + "]！");
            }
            if (fv.max() != -1d && fieldVal > fv.max()) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值[" + fieldVal + "]大于最大值[" + fv.max() + "]！");
            }
            boolean rs = validateIn(fieldVal, fv.in());
            if (!rs) {
                resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                        + fieldVal + "]不在范围内（ " + fv.in() + "）");
            }
            return resultVO;
        }
    };

    private static IValidator<String> newStringVal() {
        IValidator<String> validator = new IValidator<String>() {
            @Override
            public ResultVO validate(FieldCheck fv, String fieldName,
                                     String fieldVal, ResultVO resultVO) {
                resultVO = checkNullAndLen(fv, fieldName, fieldVal, resultVO);
                if (!StringUtil.isEmpty(fieldVal)
                        && !StringUtil.isEmpty(fv.regex())
                        && !fieldVal.matches(fv.regex())) {
                    String desc = fv.regexDesc();
                    if (StringUtil.isBlank(desc)) {
                        resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                                + fieldVal + "]不能匹配格式 " + fv.regex() + " ");
                    } else {
                        resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                                + fieldVal + "]不是有效的 " + desc + " 格式");
                    }
                }
                boolean rs = validateIn(fieldVal, fv.in());
                if (!rs) {
                    resultVO.addError(fv.name() + "[" + fieldName + "]的值["
                            + fieldVal + "]不在范围内（ " + fv.in() + "）");
                }
                return resultVO;
            }
        };
        return validator;
    }


    private static ResultVO checkNullAndLen(FieldCheck fv, String fieldName,
                                            String fieldVal, ResultVO resultVO) {
        if (StringUtil.isEmpty(fieldVal)) {
            //实际为空,若不为空
            if (!fv.isNullable()) {
                resultVO.addError(fv.name() + "[" + fieldName + "]为空！");
            }
            //实际为空,而又允许为空
            return resultVO;
        }
        //实际不为空，需要格式校验
        if (fv.length() > 0 && (fieldVal.length() != fv.length())) {
            resultVO.addError(fv.name() + "[" + fieldName + "]长度("
                    + fieldVal.length() + ")不符合要求(" + fv.length() + ")");
            return resultVO;
        }
        if (fv.maxLength() > 0 && (fieldVal.length() > fv.maxLength())) {
            resultVO.addError(fv.name() + "[" + fieldName + "]长度("
                    + fieldVal.length() + ")大于限制(" + fv.maxLength() + ")");
            return resultVO;
        }
        if (fv.minLength() > 0 && (fieldVal.length() < fv.minLength())) {
            resultVO.addError(fv.name() + "[" + fieldName + "]长度("
                    + fieldVal.length() + ")小于限制(" + fv.minLength() + ")");
            return resultVO;
        }
        return resultVO;
    }

    private static boolean validateDate(String dateStr, String pattern) {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
            Date date = dateFormat.parse(dateStr);
            String pStr = dateFormat.format(date);
            return pStr.equals(dateStr);
        } catch (ParseException e) {
            return false;
        }
    }

    private static boolean validateIn(Object o, String pattern) {
        List<String> std = null;
        if (StringUtil.isBlank(pattern)) {
            //验证标准都存在，即不需要验证
            return true;
        } else {
            String[] s = pattern.split(",");
            std = Arrays.asList(s);
            if (std == null || std.size() == 0) {
                return true;
            }
        }
        if (o instanceof String) {
            if (!std.contains(o)) {
                return false;
            }
        } else if ((o instanceof Integer) || (o instanceof Double)) {
            String strO = o + "";
            if (!std.contains(strO)) {
                return false;
            }

        } else {
            //不验证，默认通过
            return true;
        }
        return true;
    }

}
